package web;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

import IO.Log;
import IO.SystemInfo;

import data.Show;
import data.Status.StatusEnum;

public class Downloader extends Thread 
{
	private Show show;
	private boolean wasSuccessful;
	
	public Downloader(Show s)
	{
		this.show = s;
		this.run();
	}
	
	public void run()
	{
		this.downloadTorrent();
	}
	
	public boolean downloadTorrent()
	{
		wasSuccessful = true;
		while(wasSuccessful)
		{
			long loopTimeout = 1000 * 60 * 5; //5 minutes
			String torrentFilename = show.getShowName();
			torrentFilename.replace(" ", ".");
			torrentFilename += " ";
			torrentFilename = torrentFilename + "s" + show.getSelectedSeason().getSeasonNumber();
			torrentFilename = torrentFilename + "e" + show.getEpisodeToDownload().getEpisodeNumber() + ".torrent";
			String torrentFullPath = SystemInfo.getTorrentDirectory() + torrentFilename;
			try
			{
				long start = System.currentTimeMillis();
				int bufferSize = 153600;//150kilobytes
				
				URL url = new URL(show.getEpisodeToDownload().getTorrentURL());
				url.openConnection();
				InputStream reader = url.openStream();
				
				FileOutputStream writer = new FileOutputStream(torrentFullPath);
				byte[] buffer = new byte[bufferSize];
				int totalBytesRead = 0;
				int bytesRead = 0;
				
				while ((bytesRead = reader.read(buffer)) > 0)
				{
					//Check if we timed out
					if ((System.currentTimeMillis() - start) > loopTimeout)
					{
						wasSuccessful = false;
						break;
					}
					
					writer.write(buffer, 0, bytesRead);
					buffer = new byte[bufferSize];
					totalBytesRead += bytesRead;
				}
				
				if(wasSuccessful)
				{	
					Log.println("Downloading "+show.getShowName()+": "+show.getSelectedSeason().getSelectedEpisode().getEpisodeTitle());
					//Log.println("The torrent download completed in " + downloadTime/1000 + " seconds...\nBitchin!");
					//hot diggedy damn we downloaded it!  Better make that show go to the next episode
					show.getEpisodeToDownload().setDownloaded(true);
					if(!show.goToNextEpisode())
					{
						show.setStatus(StatusEnum.HOLD);
						wasSuccessful = false;
					}
				}
				else
				{
					Log.println("Sonny couldn't download your torrent.  U mad?");
				}
				
				reader.close();
				writer.close();
			}
			catch(FileNotFoundException e)
			{
				wasSuccessful = false;
				Log.printErrorln("Unable to open torrent url.");
			}
			catch (Exception e)
			{
				wasSuccessful = false;
				//will this need to cleanup the effed up torrent file?
			}
		}
		return wasSuccessful;
	}
}
